package com.dofast.bt.mvp.view.fragment.mian;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.dofast.bt.R;
import com.dofast.bt.base.BaseFragment;
import com.dofast.bt.bean.MobDataBean;
import com.dofast.bt.comment.Constant;
import com.dofast.bt.mvp.view.activity.my.CollectArticleListActivity;
import com.dofast.bt.mvp.view.activity.my.CollectGoodsListActivity;
import com.dofast.bt.mvp.view.activity.my.CollectStoreListActivity;
import com.dofast.bt.mvp.view.activity.my.MessageListActivity;
import com.dofast.bt.mvp.view.activity.my.MyOrderListActivity;
import com.dofast.bt.util.Helper;
import com.dofast.bt.util.Utility;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.smssdk.EventHandler;
import cn.smssdk.SMSSDK;

/**
 * username:Created by hsj on 2016/12/7 0007.
 * class：
 * 类描述：我
 */

public class MyFragment extends BaseFragment implements TextWatcher {

    @BindView(R.id.iv_head)
    ImageView ivHead;

    @BindView(R.id.tv_login)
    TextView tvLogin;
    @BindView(R.id.icon_shop)
    ImageView iconShop;
    @BindView(R.id.tv_shop)
    TextView tvShop;
    @BindView(R.id.ll_shop)
    LinearLayout llShop;
    @BindView(R.id.icon_baobei)
    ImageView iconBaobei;
    @BindView(R.id.tv_baobei)
    TextView tvBaobei;
    @BindView(R.id.ll_baobei)
    LinearLayout llBaobei;
    @BindView(R.id.icon_collect)
    ImageView iconCollect;
    @BindView(R.id.tv_collect)
    TextView tvCollect;
    @BindView(R.id.ll_collect)
    LinearLayout llCollect;
    @BindView(R.id.icon_order)
    ImageView iconOrder;
    @BindView(R.id.tv_order)
    TextView tvOrder;
    @BindView(R.id.ll_order)
    LinearLayout llOrder;
    @BindView(R.id.icon_notice)
    ImageView iconNotice;
    @BindView(R.id.tv_notice)
    TextView tvNotice;
    @BindView(R.id.ll_notice)
    LinearLayout llNotice;
    private EditText et1;
    private EditText et2;
    private EditText et3;
    private EditText et4;

    private String phone = "";
    private String yzm = "";
    private Dialog phoneDialog;
    private Dialog yzmDialog;
    TextView btnGetCode;
    private static final int TIME_MOVE = 0x5001;//倒计时
    private int currentSecond = 59;
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            int event = msg.arg1;
            int result = msg.arg2;
            Object data = msg.obj;
            Log.e("result", "result=" + result);
            Log.e("event", "event=" + event);
            Log.e("data", "data=" + data);
            switch (msg.what) {
                case TIME_MOVE:
                    if (currentSecond > 0) {
                        btnGetCode.setText("重新获取(" + currentSecond + ")");
                        currentSecond--;
                        handler.sendEmptyMessageDelayed(TIME_MOVE, 1000);
                    } else {
                        btnGetCode.setText("获取验证码");
                        btnGetCode.setEnabled(true);
                        currentSecond = 59;
                    }
                    break;
            }

            if (result == SMSSDK.RESULT_COMPLETE) {

                if (event == SMSSDK.EVENT_SUBMIT_VERIFICATION_CODE) {
                    //验证成功
                    Helper.showToast("登录成功");
                    Log.i("info", "验证码成功" + result + data);
                    tvLogin.setText(phone);
                    currentSecond = 0;
                    yzmDialog.dismiss();
                    phoneDialog.dismiss();

                } else if (event == SMSSDK.EVENT_GET_VERIFICATION_CODE) {
                    //验证码已发送
                    Helper.showToast("验证码已发送");
                    Log.i("info", "验证码已发送");
                }
            } else {
                if (null != data) {
                    Helper.showToast("输入的验证码有误！");
                }
            }

        }
    };

    @Override
    protected int getLayoutResourceId() {
        return R.layout.fragment_my;
    }

    @Override
    protected void initView() {
        SMSSDK.initSDK(getActivity(), Constant.APPKEY, Constant.APPSECRET);
    }

    @Override
    protected void initData() {
        initSDK();
    }

    private void initSDK() {
        EventHandler eventHandle = new EventHandler() {
            @Override
            public void afterEvent(int event, int result, Object data) {

                Message msg = new Message();
                msg.arg1 = event;
                msg.arg2 = result;
                msg.obj = data;
                handler.sendMessage(msg);
            }
        };
        SMSSDK.registerEventHandler(eventHandle);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    /**
     * 显示电话对话框
     */
    private void phoneDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_phone, null, false);
        phoneDialog = new Dialog(getActivity(), R.style.popupWindowStyle);
        phoneDialog.setContentView(view, new ViewGroup.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
        phoneDialog.setCanceledOnTouchOutside(false);
        phoneDialog.show();
        ImageView back = (ImageView) view.findViewById(R.id.iv_back);
        final EditText etPhone = (EditText) view.findViewById(R.id.et_phone);
        final Button btnNext = (Button) view.findViewById(R.id.btn_next);
        btnNext.setClickable(false);
        etPhone.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (s.length() == 11) {
                    btnNext.setBackgroundResource(R.drawable.shap_btn_blue2);
                    btnNext.setClickable(true);
                } else {
                    btnNext.setClickable(false);
                    btnNext.setBackgroundResource(R.drawable.shap_btn_gred2);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                phoneDialog.dismiss();
            }
        });
        btnNext.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //下一步邏輯處理
                phone = etPhone.getText().toString().trim();
                if (Utility.isMobileNO(phone)) {
                    showPwdDialog();
                } else {
                    Helper.showToast("您输入的手机号码有误！");
                }
            }
        });

    }

    /**
     * 验证码对话框
     */
    private void showPwdDialog() {
        View view = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_pwd, null, false);
        yzmDialog = new Dialog(getActivity(), R.style.popupWindowStyle);
        yzmDialog.setContentView(view, new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
        yzmDialog.setCanceledOnTouchOutside(true);
        yzmDialog.show();
        ImageView back = (ImageView) view.findViewById(R.id.iv_back);
        ImageView delete = (ImageView) view.findViewById(R.id.iv_delete);
        et1 = (EditText) view.findViewById(R.id.pwd1);
        et2 = (EditText) view.findViewById(R.id.pwd2);
        et3 = (EditText) view.findViewById(R.id.pwd3);
        et4 = (EditText) view.findViewById(R.id.pwd4);
        TextView tvPhone = (TextView) view.findViewById(R.id.tv_phone);
        Button btnOk = (Button) view.findViewById(R.id.btn_ok);
        tvPhone.setText(phone);
        btnGetCode = (TextView) view.findViewById(R.id.tv_time);
        et1.addTextChangedListener(this);
        et2.addTextChangedListener(this);
        et3.addTextChangedListener(this);
        et4.addTextChangedListener(this);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yzmDialog.dismiss();
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                yzmDialog.dismiss();
                phoneDialog.dismiss();
            }
        });
        btnGetCode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送验证码
                SMSSDK.getVerificationCode("86", phone);
                btnGetCode.setEnabled(false);
                btnGetCode.setText("重新获取(60)");
                handler.sendEmptyMessageDelayed(TIME_MOVE, 1000);
            }
        });
        btnOk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String code = et1.getText().toString().trim() + et2.getText().toString().trim() + et3.getText().toString().trim() + et4.getText().toString().trim();
                if (!TextUtils.isEmpty(code)) {
                    //验证验证码
                    SMSSDK.submitVerificationCode("86", phone, code);
                    Log.i("info", "phone" + phone + "code" + code);
                }

            }
        });
    }

    @OnClick({R.id.iv_head, R.id.tv_login, R.id.ll_shop, R.id.ll_baobei, R.id.ll_collect, R.id.ll_order, R.id.ll_notice})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_head:
                //// TODO: 2016/12/9 0009  修改头像
                phoneDialog();
                break;
            case R.id.tv_login:
                //// TODO: 2016/12/9 0009  登陆功能
                phoneDialog();
                break;
            case R.id.ll_shop:
                // TODO: 2016/12/9 0009 关注的茶铺功能
                Intent intent = new Intent(getActivity(), CollectStoreListActivity.class);
                startActivity(intent);
                break;
            case R.id.ll_baobei:
                // TODO: 2016/12/9 0009
                Intent intent1 = new Intent(getActivity(), CollectGoodsListActivity.class);
                startActivity(intent1);
                break;
            case R.id.ll_collect:
                // TODO: 2016/12/9 0009 收藏的文章功能
                Intent intent3 = new Intent(getActivity(), CollectArticleListActivity.class);
                intent3.putExtra("word", true);
                startActivity(intent3);
                break;
            case R.id.ll_order:
                // TODO: 2016/12/9 0009 我的订单功能
                Intent intent4 = new Intent(getActivity(), MyOrderListActivity.class);
                startActivity(intent4);
                break;
            case R.id.ll_notice:
                // TODO: 2016/12/9 0009 消息中心功能

                Intent intent5 = new Intent(getActivity(), MessageListActivity.class);
                startActivity(intent5);
                break;
        }
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        SMSSDK.unregisterAllEventHandler();
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (s.toString().trim().length() == 1) {
            if (et1.isFocused()) {
                et1.clearFocus();
                et2.requestFocus();
            } else if (et2.isFocused()) {
                et2.clearFocus();
                et3.requestFocus();
            } else if (et3.isFocused()) {
                et3.clearFocus();
                et4.requestFocus();
            } else if (et4.isFocused()) {
                et4.clearFocus();
            }
        }
    }
}
